package com.example.models.managers;

import com.example.models.DatabaseInfo;
import com.example.models.enteties.Topic;
import com.example.models.enteties.User;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: dlernatovich
 * Date: 7/12/12
 * Time: 4:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class Loginer implements DatabaseInfo {

    private String username = "";
    private String password = "";
    private Connection connection;
    private PreparedStatement ps;
    private ResultSet rs;
    private List<Topic> topics = new ArrayList<Topic>();

    public Loginer() {
    }

    public User getCurrentUser() throws ClassNotFoundException, SQLException {
        User user = new User();

        Class.forName(DRIVER_NAME);
        connection = (Connection) DriverManager.getConnection(URL_SERVER, USERNAME, PASSWORD);
        ps = (PreparedStatement) connection.prepareStatement("SELECT * FROM `users` " +
                "WHERE `user_name`=? AND `user_password`=?");
        ps.setString(1, this.username);
        ps.setString(2, this.password);
        rs = ps.executeQuery();

        if (rs.first() == false) {
            throw new SQLException();
        }

//        ps.close();
//        rs.close();

        user.setId(rs.getInt(1));
        user.setUsername(rs.getString(2));
        user.setPassword(rs.getString(3));
        user.setEmail(rs.getString(4));

        ps = (PreparedStatement) connection.prepareStatement("SELECT * FROM topics ORDER BY id");
        rs = ps.executeQuery();
        rs.first();

        do {
            topics.add(new Topic(rs.getLong(1), rs.getString(2), rs.getString(3)));
        } while (rs.next());

        closeConnection();

        return user;
    }

    public void closeConnection() throws SQLException {
        connection.close();
        ps.close();
        rs.close();
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Topic> getTopics() {
        return topics;
    }
}
